import {uploadActionUrl} from '../utils/tools'
import React, {useState} from 'react'
import {PlusOutlined} from '@ant-design/icons'
import {Modal, Upload} from 'antd'
import {useEffect} from 'react'

const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = (error) => reject(error)
    })
const ManyUpload = ({fileList, setFileList}) => {
    const [previewOpen, setPreviewOpen] = useState(false)
    const [previewImage, setPreviewImage] = useState('')
    const [previewTitle, setPreviewTitle] = useState('')

    const handleCancel = () => setPreviewOpen(false)
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj)
        }
        setPreviewImage(file.url || file.preview)
        setPreviewOpen(true)
        setPreviewTitle(
            file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
        )
    }
    const handleChange = ({fileList: newFileList}) => setFileList(newFileList)
    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none'
            }}
            type="button"
        >
            <PlusOutlined/>
            <div
                style={{
                    marginTop: 8
                }}
            >
                上传图片
            </div>
        </button>
    )
    useEffect(() => {
        console.log(fileList)
    }, [fileList])
    return (
        <>
            <Upload
                action={uploadActionUrl}
                //服务器接口的参数名称
                name="file"
                listType="picture-card"
                fileList={fileList}
                onPreview={handlePreview}
                onChange={handleChange}
            >
                {fileList.length >= 6 ? null : uploadButton}
            </Upload>
            <Modal
                open={previewOpen}
                title={previewTitle}
                footer={null}
                onCancel={handleCancel}
            >
                <img
                    alt="示例图片"
                    style={{
                        width: '100%'
                    }}
                    src={previewImage}
                />
            </Modal>
        </>
    )
}
export default ManyUpload
